#!/bin/bash

# 颜色
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
plain='\033[0m'
script_version="2021.04.09.0"

function info { echo -e "\e[32m[info] $*\e[39m"; }
function warn  { echo -e "\e[33m[warn] $*\e[39m"; }
function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" != "$1"; }

# 变量
## 安装必备依赖
Ubunt_Debian_Requirements="curl socat jq avahi-daemon net-tools network-manager qrencode apparmor apparmor-utils"
## 获取系统用户用作添加至 docker 用户组
users=($(cat /etc/passwd | awk -F: '$3>=500' | cut -f 1 -d :| grep -v nobody))
users_num=${#users[*]}

## 这个方法抄袭自 https://github.com/teddysun/shadowsocks_install
check_sys(){
    if [[ -f /etc/redhat-release ]]; then
        release="centos"
        systemPackage="yum"
    elif grep -Eqi "raspbian" /etc/*-release ; then
        kernel_version=$(uname -r | grep -oP '\d+\.\d+\.\d+')
        if version_lt "${kernel_version}" "5.4.79";then
            error "当前 ${kernel_version} 内核系统暂不支持 apparmor 内核模块需要更新内核(≥ 5.4.79)。"
        fi
        release="raspbian"
        systemPackage="apt"
        systemCodename=$(grep "VERSION_CODENAME" /etc/*-release | awk -F '=' '{print $2}')
    elif grep -Eqi "ubuntu" /etc/issue; then
        release="ubuntu"
        systemPackage="apt"
        systemCodename=$(grep "VERSION_CODENAME" /etc/*-release | awk -F '=' '{print $2}')
    elif grep -Eqi "debian" /etc/issue; then
        release="debian"
        systemPackage="apt"
        systemCodename=$(grep "VERSION_CODENAME" /etc/*-release | awk -F '=' '{print $2}')
    elif grep -Eqi "centos|red hat|redhat" /etc/issue; then
        release="centos"
        systemPackage="yum"
    elif grep -Eqi "centos|red hat|redhat" /proc/version; then
        release="centos"
        systemPackage="yum"
    fi
}
## 切换安装源
replace_source(){
    if [[ -z ${systemCodename} ]]; then
        error "由于无法确定系统版本，故请手动切换系统源，切换方法参考清华源使用方法：http://mirrors.ustc.edu.cn/help/"
    fi
    [[ ! -f /etc/apt/sources.list.bak ]] && warn "备份系统源文件为 /etc/apt/sources.list.bak" && mv /etc/apt/sources.list /etc/apt/sources.list.bak

    # 清华源

    case $(uname -m) in
        "x86_64" | "i686" | "i386" )
            # debian from x86_64
            if [[ ${release} == "debian" ]]; then
                {
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian/ ${systemCodename} main contrib non-free"
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian/ ${systemCodename}-updates main contrib non-free"
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian/ ${systemCodename}-backports main contrib non-free"
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian-security ${systemCodename}/updates main contrib non-free"
                } > /etc/apt/sources.list
            fi

            # Ubuntu from x86_64
            if [[ ${release} == "ubuntu" ]]; then
                {
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ ${systemCodename} main restricted universe multiverse"
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ ${systemCodename}-updates main restricted universe multiverse"
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ ${systemCodename}-backports main restricted universe multiverse"
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ ${systemCodename}-security main restricted universe multiverse"
                } > /etc/apt/sources.list
            fi
            ;;
        "arm" | "armv7l" | "armv6l" | "aarch64" | "armhf" | "arm64" | "ppc64el")
            if [[ -f /etc/apt/sources.list.d/armbian.list ]] ;then
                warn "发现 armbian 源，替换清华源，如需要恢复请自行到 /etc/apt/sources.list.d/ 文件夹中删除后缀名 \".bak\""
                cp /etc/apt/sources.list.d/armbian.list /etc/apt/sources.list.d/armbian.list.bak
                sed -i 's|http[s]*://apt.armbian.com|http://mirrors.tuna.tsinghua.edu.cn/armbian|g' /etc/apt/sources.list.d/armbian.list
            fi

            # debian from ARM
            if [[ ${release} == "debian" ]]; then
                {
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian/ ${systemCodename} main contrib non-free"
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian/ ${systemCodename}-updates main contrib non-free"
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian/ ${systemCodename}-backports main contrib non-free"
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian-security ${systemCodename}/updates main contrib non-free"
                } > /etc/apt/sources.list
            fi

            # Ubuntu from ARM
            if [[ ${release} == "ubuntu" ]]; then
                {
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/ ${systemCodename} main restricted universe multiverse"
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/ ${systemCodename}-updates main restricted universe multiverse"
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/ ${systemCodename}-backports main restricted universe multiverse"
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/ ${systemCodename}-security main restricted universe multiverse"
                } > /etc/apt/sources.list
            fi

            if [[  ${release} == "raspbian" ]]; then
                {
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/raspbian/raspbian/ ${systemCodename} main non-free contrib rpi"
                    echo "deb-src http://mirrors.tuna.tsinghua.edu.cn/raspbian/raspbian/ ${systemCodename} main non-free contrib rpi"
                } > /etc/apt/sources.list
                if [[ -f "/etc/apt/sources.list.d/raspi.list" ]]; then
                    echo "deb http://mirrors.tuna.tsinghua.edu.cn/raspberrypi/ ${systemCodename} main" > "/etc/apt/sources.list.d/raspi.list"
                fi
            fi
            ;;
        *)  error "[ERROR]: 由于无法获取系统架构，故此无法切换系统源，请跳过系统源切换。"
            ;;
    esac

    apt update
    if [[ $? -ne 0 ]]; then
        mv /etc/apt/sources.list.bak /etc/apt/sources.list
        error "[ERROR]: 系统源切换错误，请检查网络连接是否正常，脚本退出"
    fi
}

## 更新系统
update_system(){
    if [[ ${release} == "debian" ]] || [[ ${release} == "ubuntu" ]] || [[ ${release} == "raspbian" ]]; then
        apt upgrade -y
        if [[ $? != 0 ]]; then
            error "[ERROR]: 系统更新失败，脚本退出。"
        fi
        info "系统更新成功。"
    fi
    if [[ ${release} == "ubuntu" ]] ; then
        add-apt-repository main
        add-apt-repository universe
        add-apt-repository restricted
        add-apt-repository multiverse
        apt update
    fi
}

## 定义 Ubuntu 和 Debian 依赖
info "安装 hassio 必要依赖....."
## apt 安装依赖方法
apt_install(){
    apt update
    apt install -y ${*}
    if [[ $? -ne 0 ]];then
        error "安装${*}失败，请将检查上方安装错误信息。"
    fi
}

apt_install ${Ubunt_Debian_Requirements}
## 修改 docker 源
change_docker_registry(){
    if [ ! -d /etc/docker ];then
        mkdir -p /etc/docker
    fi
cat << EOF > /etc/docker/daemon.json 
{ 
    "log-driver": "journald",
    "storage-driver": "overlay2",
    "registry-mirrors": [ 
    "https://hub-mirror.c.163.com",
    "https://docker.mirrors.ustc.edu.cn"
    ]
}
EOF
    systemctl daemon-reload
    systemctl restart docker > /dev/null
    info "切换国内源完成"
}
#通过默认网关的网卡接口获取本机有效的IP地址
get_ipaddress(){
    local device_name=$(netstat -rn | grep -e '^0\.0\.0\.0' | awk '{print $8}' | head -n1)
    ipaddress=$(ifconfig ${device_name} | grep "inet"| grep -v "inet6" | awk '{ print $2}')
    if ! check_ip ${ipaddress} ;then
        ipaddress='你的服务器的IP地址'
    fi
}
# 检查出国旅游连通性
check_proxy_status(){
    info "正在通过访问 www.youtube.com 检查旅游环境"
    if ! wget -q --connect-timeout 20 --tries 1 --retry-connrefused  https://www.youtube.com -O /tmp/youtube ;then
        warn "旅游失败,请检查出国旅游环境."
        return 1
    fi
    return 0
}
## 检查脚本运行环境
if ! id | grep -q 'root' 2>/dev/null ;then
    error "请输入 \"sudo -s\" 切换至 root 账户运行本脚本...脚本退出"
fi
## 检查系统版本
check_sys